import { request } from '@/request';
import { useState } from 'react';
import { useDebounced, useGlobalVar } from '@/hooks';
import { InviteIcon, CheckIcon, SearchIcon } from '@/components/icons';
import { Tag } from '@/components';
import useGroupEditor from './useGroupEditor';
import { useQuery } from 'react-query';

import _ from 'lodash';

const Group = () => {
   const { user } = useGlobalVar();
   const { initParams, isNew, addGroup, updateGroup, groupId } =
      useGroupEditor();

   const [data, setData] = useState({
      name: initParams.name,
      budget: initParams.budget,
      desc: initParams.desc,
   });
   const [members, setMembers] = useState(initParams.members);
   const [keyword, setKeyword] = useState('');
   const [results, setResults] = useState([]);

   useQuery(`group`, async () => request(`/groups/${groupId}`,{
      success:(data)=>{
         const { budget, desc, group_name, members } = data
         setData({
            name:group_name,
            budget,
            desc
         })
         setMembers(members)
      }
   }), {
      enabled: groupId !== undefined,
      staleTime: 0,
   });

   const handleChange = (e) => {
      const { name, value } = e.target;
      setData((data) => ({ ...data, [name]: value }));
   };

   // 搜索成员
   const handleSearch = useDebounced(async (value) => {
      const res = await request('/users', {
         params: {
            keyword: value,
         },
      });
      setResults(res.data.list);
   }, 1000);

   const handleChangeKeyword = (e) => {
      const { value } = e.target;
      setKeyword(value);
      handleSearch(value);
   };

   // 邀请成员
   const handleInvite = (isIn, user) => {
      if (isIn) return;
      setMembers([user, ...members]);
   };
   const handleClose = (userId) => {
      setMembers(members.filter((item) => item._id !== userId));
   };

   // 提交
   const handleSubmit = () => {
      const obj = {
         group_name: data.name,
         budget: data.budget,
         desc: data.desc,
         members: members.map((item) => item._id),
      };
      if (isNew) {
         addGroup(obj);
      } else {
         updateGroup(obj);
      }
   };

   return (
      <>
         <div className="w-full bg-white rounded-md shadow-sm p-4 space-y-2">
            <div className="form-item-content">
               <label>名称</label>
               <input value={data.name} name="name" onChange={handleChange} />
            </div>
            <div className="form-item-content">
               <label>人均预算</label>
               <input
                  value={data.budget}
                  name="budget"
                  onChange={handleChange}
               />
            </div>
            <div className="form-item-content items-start">
               <label>描述</label>
               <textarea
                  value={data.desc}
                  name="desc"
                  onChange={handleChange}
               />
            </div>
            <div className="form-item-content items-start">
               <label className="w-1/4">成员列表</label>
               <div className="space-x-3">
                  <Tag key={user._id}>{user.username}</Tag>
                  {members
                     .filter((item) => item._id !== user._id)
                     .map((item) => (
                        <Tag
                           key={item._id}
                           showClose={true}
                           onClose={handleClose.bind(null, item._id)}
                        >
                           {item.username}
                        </Tag>
                     ))}
               </div>
            </div>
            <div className="form-item-content items-start">
               <label className="w-1/4">邀请成员</label>
               <div>
                  <span className="flex bg-zinc-100 items-center pl-2">
                     <SearchIcon size={18} />
                     <input
                        placeholder="输入用户名/手机号"
                        value={keyword}
                        onChange={handleChangeKeyword}
                     />
                  </span>
                  <div className="color-disabled p-2 border border-dashed border-slate-200 mt-2">
                     {results.length !== 0 ? (
                        results.map((item) => {
                           const isIn = members.find(
                              (user) => user._id === item._id
                           );
                           return (
                              <div
                                 key={item._id}
                                 className="flex justify-between"
                              >
                                 <span className="text-sm">
                                    {item.username}
                                 </span>
                                 <span
                                    className="text-sm"
                                    onClick={handleInvite.bind(
                                       null,
                                       isIn,
                                       item
                                    )}
                                 >
                                    {isIn ? (
                                       <CheckIcon size={18} type="primary" />
                                    ) : (
                                       <InviteIcon size={18} type="primary" />
                                    )}
                                 </span>
                              </div>
                           );
                        })
                     ) : (
                        <span>无结果</span>
                     )}
                  </div>
               </div>
            </div>
         </div>
         <div className="btn mt-4" onClick={handleSubmit}>
            确认
         </div>
      </>
   );
};
export default Group;
